package com.onnext.androidsdk.module.view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Scroller;
import com.onnext.androidsdk.util.LogUtil;

public class CustomView extends View {

    VelocityTracker velocityTracker;
    private Scroller scroller;
    private int startX;
    private int startY;
    public CustomView(Context context) {
        this(context, null);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        ViewConfiguration.get(context).getScaledTouchSlop();
        scroller = new Scroller(context);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                velocityTracker = VelocityTracker.obtain();
                break;
            case MotionEvent.ACTION_MOVE:
                velocityTracker.addMovement(event);
                scrollTo((int)event.getX(), (int)event.getY());
                invalidate();
                LogUtil.e("ACTION_MOVE "+event.getX());
                break;
            case MotionEvent.ACTION_UP:
                startX = (int) event.getX();
                startY = (int) event.getY();
                velocityTracker.computeCurrentVelocity(1000);
                int x = (int) velocityTracker.getXVelocity();
                int y = (int) velocityTracker.getYVelocity();
                LogUtil.e(x + "   " + y);
                velocityTracker.recycle();
                break;
        }
        return true;
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (scroller.computeScrollOffset()) {
            scrollTo(scroller.getCurrX(), scroller.getCurrY());
            invalidate();
        }
    }

    public void start(int duration) {
        scroller.startScroll(0, 0, 800, 1800, duration);
        invalidate();
    }
}
